<template>
	<view class="login-container">
		<!-- 顶部logo -->
		<view class="logo-area">
			<image class="logo" src="/static/logo.png" mode="aspectFit"></image>
		</view>

		<!-- 登录表单 -->
		<view class="form-area">
			<view class="title">欢迎登录</view>

			<!-- 微信登录按钮 -->
			<button class="wx-login-btn" @click="handleWechatLogin" :loading="wxAuthLoading">
			<!-- 	<image class="wx-icon" src="/static/wechat.png" mode="aspectFit"></image> -->
				<text>微信一键登录</text>
			</button>

			<!-- 协议提示 -->
			<!-- <view class="agreement">
				登录即表示您已同意
				<text class="link" @click="navigateToAgreement('user')">《用户协议》</text>
				和
				<text class="link" @click="navigateToAgreement('privacy')">《隐私政策》</text>
			</view> -->
		</view>
	</view>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import user from "@/api/user.js";

export default {
	data() {
		return {
			wxAuthLoading: false, // 微信授权加载状态
			userInfo: null,
		};
	},
	computed: mapGetters(["isLogin", "uid"]),
	onLoad() {
		// 检查是否已登录
		if (uni.getStorageSync('token')) {
			this.redirectToHome();
		}
	},
	methods: {
		...mapActions(["login", "setUserInfo"]),
		
		// 跳转到首页
		redirectToHome() {
			uni.switchTab({
				url: "/pages/index/index",
			});
		},

		// 跳转协议页面
		navigateToAgreement(type) {
			uni.navigateTo({
				url: `/pages/agreement/agreement?type=${type}`,
			});
		},

		// 获取URL参数
		getQueryString(name) {
			const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			const r = window.location.search.substr(1).match(reg);
			if (r != null) {
				return decodeURIComponent(r[2]);
			}
			return null;
		},

		// 处理微信登录
		async handleWechatLogin() {
			this.wxAuthLoading = true;
			
			// H5环境微信网页授权登录
			// #ifdef H5
			const appid = 'wx6bd80db273bdbad9'; // 替换为你的微信AppID
			console.log(window.location.origin,'window.location.origin');
			
			const redirectUri = encodeURIComponent(
				// `${window.location.origin}/login?type=wx`
				`https://d-dazi.bigchun.com/api/user/third?platform=wechat&zhitui_id=1`		
			);
			const wxAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
			window.location.href = wxAuthUrl;
			if(){
				this.handleLoginSuccess(res.data.data.userinfo.token, res.data.data.userinfo,res.data.data.thirdinfo);
			}
			// #endif
			
		},
		
		// 统一处理登录成功
		handleLoginSuccess(token, userInfo,thirdinfo) {
			// 保存token和用户信息
			uni.setStorage({ key: 'token', data: token });
			uni.setStorage({ key: 'userInfo', data: userInfo });
			uni.setStorage({ key: 'thirdinfo', data: thirdinfo });
			// 更新Vuex状态
			this.$store.commit('LOGIN', {
				token: token,
				uid: userInfo.id || userInfo.uid
			});
			this.$store.commit('UPDATE_USERINFO', userInfo);
			
			uni.showToast({ title: '登录成功', icon: 'success' });
			setTimeout(() => this.redirectToHome(), 1500);
		},
		
		handleLoginError(error) {
			const message = error?.data?.msg || error?.message || '登录失败';
			uni.showToast({ title: message, icon: 'none' });
		}
	},
	onShow() {
		// H5环境检查微信授权回调
		// #ifdef H5
		const code = this.getQueryString("code");
		const type = this.getQueryString("type");
		if (code && type === "wx" && !!uni.getStorageSync('token')) {
			this.exchangeWxCode(code);
		}
		// #endif
	},
	
	// 用code换取token (H5环境)
	async exchangeWxCode(code) {
		try {
			uni.showLoading({
				title: "登录中...",
				mask: true,
			});

			const res = await user.userThirdLogin({
				code: code,
				source: "wechat",
			});

			if (res.response.statusCode === 200) {
				this.handleLoginSuccess(res.data.data.userinfo.token, res.data.data.userinfo);
			} else {
				this.handleLoginError(res);
			}
		} catch (error) {
			console.error("微信登录失败", error);
			this.handleLoginError(error);
		} finally {
			this.wxAuthLoading = false;
			uni.hideLoading();
		}
	},
};
</script>

<style lang="scss" scoped>
.login-container {
	padding: 0 60rpx;
	box-sizing: border-box;
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #fff;

	.logo-area {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;

		.logo {
			width: 200rpx;
			height: 200rpx;
			border-radius: 20rpx;
		}
	}

	.form-area {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		padding-bottom: 100rpx;

		.title {
			font-size: 48rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 80rpx;
			text-align: center;
		}

		.wx-login-btn {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 45rpx;
			background-color: #07C160;
			color: #fff;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 40rpx;
			
			.wx-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 15rpx;
			}

			&:after {
				border: none;
			}
		}

		.agreement {
			margin-top: 40rpx;
			font-size: 24rpx;
			color: #999;
			text-align: center;

			.link {
				color: #07C160;
			}
		}
	}
}
</style>
